package com.ad.aidai.db.dao;

import com.ad.aidai.bean.User;
import com.ad.aidai.db.DBManager;
import com.ad.aidai.db.greendao.UserDao;

import java.util.List;

/**
 * 数据库操作(用户表)
 * <p>
 * Created by Yusxon on 16/12/2.
 */

public class MyUserDao {

    public static MyUserDao sInstance;

    private MyUserDao() {

    }

    public static MyUserDao getUserDao() {
        if (sInstance == null) {
            synchronized (MyUserDao.class) {
                if (sInstance == null) {
                    sInstance = new MyUserDao();
                }
            }
        }
        return sInstance;
    }

    /**
     * 查询用户信息
     *
     * @return
     */
    public User query() {
        List<User> userList = DBManager.getDB().getDaoSession().getUserDao().queryBuilder().build().list();
        User user = null;
        if (userList.size() > 0) {
            user = userList.get(0);
        }
        return user;
    }

    /**
     * 插入用户信息
     *
     * @param user
     */
    public void insert(User user) {
        UserDao dao = DBManager.getDB().getDaoSession().getUserDao();
        if (user != null) {
            List<User> list = dao.queryBuilder().build().list();
            if (list.size() > 0) {
                if (list.get(0).getUserId().equals(user.getUserId())) {
                    save(user);
                    return;
                } else {
                    dao.delete(list.get(0));
                }
            }

            dao.insert(user);
        }
    }

    /**
     * 保存用户信息(如果用户存在,则会更新,否则插入新信息)
     *
     * @param user
     */
    public void save(User user) {
        UserDao dao = DBManager.getDB().getDaoSession().getUserDao();
        if (user != null) {
            dao.save(user);
        }
    }

    /**
     * 更新用户信息
     *
     * @param user
     */
    public void update(User user) {
        UserDao dao = DBManager.getDB().getDaoSession().getUserDao();
        if (user != null) {
            dao.update(user);
        }
    }

    /**
     * 删除用户信息
     *
     * @param user
     */
    public void delete(User user) {
        UserDao dao = DBManager.getDB().getDaoSession().getUserDao();
        if (user != null) {
            dao.delete(user);
        }
    }

    /**
     * 删除所有用户信息
     */
    public void deleteAll() {
        DBManager.getDB().getDaoSession().getUserDao().deleteAll();
    }
}
